<?php

namespace App\Jobs;

use App\Repository\LostRepository;
use App\Repository\UserRepository;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;

class LostAudit implements ShouldQueue
{
    use InteractsWithQueue, Queueable, SerializesModels;

    protected $lost;
    protected $repo;
    protected $user;

    /**
     * Create a new job instance.
     * @param $lost
     */
    public function __construct($lost)
    {
        $this->lost = $lost;
    }

    /**
     * Execute the job.
     * @param UserRepository $user
     * @param LostRepository $repo
     */
    public function handle(UserRepository $user, LostRepository $repo)
    {
        $this->user = $user;
        $this->repo = $repo;

        $user = $this->user->getUserByOpenId($this->lost->publisher);
        if($havePermission = $user->havePermission('lost_publish') OR !$this->lost->number){

            $this->auditLost($havePermission);

            if($this->lost->number){
                dispatch(new LostNotify($this->lost));
            }
        }else{
            $data = [
                'first' => '你好，你有一条待审核通知',
                'keyword1' => $this->lost->user->number,
                'keyword2' => $this->lost->created_at->toDateTimeString(),
                'keyword3' => $this->lost->description,
                'remark' => '请及时审核，谢谢',
            ];
            $users = $this->repo->getLostAuditor();
            if($users->count() > 0){
                $users->each(function($user) use ($data){
                    $openId = $user->open_id;
                    dispatch(new SendTemplate($data, env('APP_URL') . 'lost', $openId, 'lost_audit'));
                });
            }
        }
    }

    private function auditLost($havePermission)
    {
        $this->lost->status = 1;
        $this->lost->role = $havePermission ? 1 : 0;
        $this->lost->save();
    }
}
